<template>
  <div class="editor-container" :class="{ readonly: isReadOnly }" @contextmenu.prevent="handleEditorContextMenu">
    <div class="editor-toolbar">
      <div class="toolbar-left">
        <el-button link @click="goBack">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
      </div>
      <div class="toolbar-right">
        <!-- 版本管理按钮 -->
        <el-button
          v-if="currentDocument"
          size="small"
          @click="showCreateVersionDialog = true"
        >
          <el-icon><DocumentAdd /></el-icon>
          创建版本
        </el-button>
        <el-button
          v-if="currentDocument"
          size="small"
          @click="showVersionHistory = true"
        >
          <el-icon><Clock /></el-icon>
          版本历史
        </el-button>
        <el-button
          v-if="currentDocument"
          size="small"
          type="success"
          @click="showVersionCompare = true"
        >
          <el-icon><Histogram /></el-icon>
          版本对比
        </el-button>
        <span class="version-info" v-if="currentDocument">
          v{{ currentDocument.currentVersion }}
        </span>
        <el-button
          v-if="canManage && !isSharedPage"
          size="small"
          @click="showPermissionManager = true"
        >
          <el-icon><Permission /></el-icon>
          权限管理
        </el-button>
        <el-button
          v-if="canManage && !isSharedPage"
          size="small"
          @click="showMemberDialog = true"
        >
          <el-icon><User /></el-icon>
          成员管理
        </el-button>
        <!-- 模式切换按钮 -->
        <el-button
          size="small"
          @click="toggleEditorMode">
          {{ isReadOnly ? '进入编辑模式' : '进入阅读模式' }}
        </el-button>
        <!-- <el-button 
          size="small"
          :type="collaborationEnabled ? 'warning' : 'primary'"
          :loading="collaborationConnecting"
          @click="toggleCollaboration"
        >
          <el-icon><Connection /></el-icon>
          {{ collaborationEnabled ? '关闭协同' : '开启协同' }}
        </el-button> -->
      </div>
      
    </div>
    <!-- 创建版本对话框 -->
    <el-dialog
      v-model="showCreateVersionDialog"
      title="创建版本节点"
      width="500px"
    >
      <el-form
        ref="versionFormRef"
        :model="versionForm"
        :rules="versionRules"
        label-width="100px"
      >
        <el-form-item label="版本名称" prop="versionName">
          <el-input
            v-model="versionForm.versionName"
            placeholder="请输入版本名称，如：v1.0"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="版本描述" prop="description">
          <el-input
            v-model="versionForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入版本描述（可选）"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateVersionDialog = false">取消</el-button>
          <el-button
            type="primary"
            :loading="creatingVersion"
            @click="handleCreateVersionClick"
          >
            创建
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限管理组件 -->
    <PermissionManager
      v-model:visible="showPermissionManager"
      :document-id="documentId"
    />

    <!-- 成员管理组件 -->
    <MemberManager
      v-model:visible="showMemberDialog"
      :docId="documentId"
      :current-user-permission="'MANAGE'"
    />

    <!-- 版本历史组件 -->
    <VersionHistory
      v-model:visible="showVersionHistory"
      :document-id="documentId"
      :current-version="currentDocument?.currentVersion"
      @version-restored="handleVersionRestored"
    />

    <!-- 版本对比组件 -->
    <VersionCompare
      v-model:visible="showVersionCompare"
      :document-id="documentId"
      :versions="documentVersions"
    />


    <!-- <div class="toolbar">
      <button @click="handleSummary" :disabled="loading">
        {{ loading ? "生成中..." : "生成AI摘要" }}
      </button>
    </div> -->

    <umo-editor ref="editorRef" v-bind="options" :saving="isSaving">
      <template #toolbar_base>
        <!-- 只在编辑模式下显示添加评论按钮 -->
        <!-- <umo-menu-button
          v-if="!isReadOnly"
          :ico="commentIcon"
          text="添加评论"
          :huge="true"
          @menu-click="handleAddComment"
        /> -->
        <umo-menu-button
          :ico="listIcon"
          text="评论列表"
          :huge="true"
          @menu-click="showCommentList = true"
        />
      </template>

      <template #bubble_menu>
        <button
          class="bubble-ai-btn"
          @click="showAIMenuFromBubble"
          style="margin-left: 8px; display: flex; align-items: center"
        >
          <svg width="16" height="16" viewBox="0 0 1024 1024">
            <circle cx="512" cy="512" r="480" fill="#1677ff" />
            <text
              x="50%"
              y="55%"
              text-anchor="middle"
              fill="#fff"
              font-size="420"
              font-family="Arial"
              dy=".3em"
            >
              AI
            </text>
          </svg>
          <span style="margin-left: 4px">AI</span>
        </button>
      </template>
      <!-- 不在 bubble_menu 插槽加AI按钮 -->
    </umo-editor>

    <!-- BubbleMenu（原有的） -->
    <!-- <BubbleMenu
      :editor="editor"
      :tippy-options="{ duration: 100 }"
      v-if="editor"
    >
    </BubbleMenu> -->

    
    

    <!-- 悬浮AI按钮，定位到BubbleMenu右侧 -->
    <button
      v-if="showBubbleAI"
      class="bubble-ai-btn-absolute"
      :style="{ top: bubbleMenuPos.y + 'px', left: bubbleMenuPos.x + 'px' }"
      @mousedown.prevent="showAIMenuFromBubble"
      @click="showAIMenuFromBubble"
      title="AI功能"
    >
      <svg width="18" height="18" viewBox="0 0 1024 1024">
        <circle cx="512" cy="512" r="480" fill="#1677ff" />
        <text
          x="50%"
          y="55%"
          text-anchor="middle"
          fill="#fff"
          font-size="420"
          font-family="Arial"
          dy=".3em"
        >
          AI
        </text>
      </svg>
      <span style="margin-left: 4px">AI</span>
    </button>

    <!-- AI功能悬浮框 -->
    <div
      v-if="aiMenuVisible"
      class="ai-menu-popup"
      :style="{ top: aiMenuPosition.y + 'px', left: aiMenuPosition.x + 'px' }"
    >
      <div style="display: flex; gap: 8px">
        <input
          v-model="aiPrompt"
          placeholder="输入你的指令或需求"
          class="ai-prompt-input"
        />
        <button
          v-if="aiPrompt"
          class="ai-btn"
          style="width: 60px; min-width: 60px; padding: 0 8px; margin-bottom: 0"
          @click="handleAIFeature('prompt')"
        >
          发送
        </button>
      </div>
      <div class="ai-menu-btn-row">
        <button @click="handleAIFeature('summary')">摘要</button>
        <button @click="handleAIFeature('continue')">续写</button>
        <button @click="handleAIFeature('polish')">润色</button>
        <button @click="aiMenuVisible = false">关闭</button>
      </div>
    </div>

    <!-- AI生成内容确认弹窗 -->
    <div
      v-if="aiResultVisible"
      class="ai-result-modal"
      :style="{
        top: aiResultPosition.y + 'px',
        left: aiResultPosition.x + 'px',
        position: 'fixed',
      }"
    >
      <div class="ai-result-modal-header" @mousedown="startDrag">
        <span>AI生成内容</span>
      </div>
      <div class="ai-result-content" v-html="aiResultHtml"></div>
      <button @click="insertAIResult">插入到文档</button>
      <button @click="aiResultVisible = false">取消</button>
    </div>

    <div v-if="summaryVisible" class="summary-sidebar">
      <h3>AI摘要</h3>
      <div class="summary-content" v-html="summaryHtml"></div>
      <button @click="summaryVisible = false" class="close-btn">关闭</button>
    </div>

    <!-- 悬浮评论按钮 -->
    <button
      v-if="showBubbleAI && !isReadOnly"
      class="bubble-ai-btn-absolute"
      :style="{ top: bubbleMenuPos.y + 'px', left: (bubbleMenuPos.x + 60)+ 'px'}"
      @mousedown.prevent="handleAddComment"
      @click="handleAddComment"      
    >
    <svg t="1751428245011" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5111" width="20" height="20"><path d="M157.568 751.296c-11.008-18.688-18.218667-31.221333-21.802667-37.909333A424.885333 424.885333 0 0 1 85.333333 512C85.333333 276.362667 276.362667 85.333333 512 85.333333s426.666667 191.029333 426.666667 426.666667-191.029333 426.666667-426.666667 426.666667a424.778667 424.778667 0 0 1-219.125333-60.501334 2786.56 2786.56 0 0 0-20.053334-11.765333l-104.405333 28.48c-23.893333 6.506667-45.802667-15.413333-39.285333-39.296l28.437333-104.288z m65.301333 3.786667l-17.258666 63.306666 63.306666-17.258666a32 32 0 0 1 24.522667 3.210666 4515.84 4515.84 0 0 1 32.352 18.944A360.789333 360.789333 0 0 0 512 874.666667c200.298667 0 362.666667-162.368 362.666667-362.666667S712.298667 149.333333 512 149.333333 149.333333 311.701333 149.333333 512c0 60.586667 14.848 118.954667 42.826667 171.136 3.712 6.912 12.928 22.826667 27.370667 47.232a32 32 0 0 1 3.338666 24.714667z m145.994667-70.773334a32 32 0 1 1 40.917333-49.205333A159.189333 159.189333 0 0 0 512 672c37.888 0 73.674667-13.173333 102.186667-36.885333a32 32 0 0 1 40.917333 49.216A223.178667 223.178667 0 0 1 512 736a223.178667 223.178667 0 0 1-143.136-51.690667z" fill="#000000" p-id="5112"></path></svg>
    </button>

    <CommentSidebar
      v-if="showCommentSidebar"
      :selectedText="selectedCommentText"
      :position="{ top: bubbleMenuPos.y, left: bubbleMenuPos.x}"
      :documentId = "documentId"
      @close="showCommentSidebar = false"
      @comment-created = comment_created
    />

    <CommentList 
    v-if="showCommentList"
    ref="commentListRef" 
    :document-id="documentId" 
    @close="showCommentList = false"
    
  />
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, computed, onMounted, onUnmounted, watch, nextTick } from "vue";
import { UmoEditor } from "@umoteam/editor";
import { marked } from "marked";
import CommentSystem from "./CommentSystem.vue";
import { UmoMenuButton } from "@umoteam/editor";
import Highlight from "@tiptap/extension-highlight";
import CommentSidebar from "@/components/editor/CommentSidebar.vue";
import { ElMessage } from "element-plus";
import { getDocumentDetail, updateDocument, getDocumentVersions } from "@/api/document.ts";
import { getUserId } from "@/utils/auth.ts";
import { useKnowledgeStore } from "@/stores/knowledge.ts";
import { storeToRefs } from "pinia";
import { useRoute, useRouter } from "vue-router";
import BubbleMenu from "@tiptap/extension-bubble-menu";
import { useDocumentStore } from "@/stores/document";
import VersionHistory from '@/components/editor/VersionHistory.vue'
import VersionCompare from '@/components/editor/VersionCompare.vue'
import type { FormInstance } from 'element-plus'
import type {Comment} from '@/types/index.ts'
import CommentList from "./CommentList.vue"
import UmoCollaboration from '@/utils/collaboration'
import type { CollaborationOptions } from '@/types/collaboration'
import PermissionManager from "@/components/permission/PermissionManager.vue";
import MemberManager from "@/components/permission/MemberManager.vue";
import {getDocPermissionsByUserId} from "@/api/permission.ts";
import { 
  ArrowLeft, 
  User, 
  Connection,
  Loading,
  DocumentAdd,
  Clock,
  Histogram,
  ArrowDown
} from '@element-plus/icons-vue'

import {getCommentListAPI} from "@/api/comment.ts"
import { CommentHighlight } from "@/utils/commentHighlight";
const route = useRoute();
const router = useRouter();

//const documentId = route.params.documentId; // 直接获取参数
const documentId = computed(() => route.params.documentId as string)  // 响应式参数
const isSaving = ref(false);
console.log("当前文档ID:", documentId.value); // 调试输出

const currentContent = ref("");
const isLoading = ref(false);

const documentStore = useDocumentStore();

// 使用一个对象来存储不同文档的模式状态
const documentModeMap = ref<Record<string, boolean>>({});

// 权限管理相关状态
const showPermissionManager = ref(false);
const canManage = ref(true);

const showMemberDialog = ref(false);
// const isReadOnly = ref(false) // 默认编辑模式
// 从documentModeMap中获取当前文档的模式状态
const isReadOnly = computed({
  get: () => documentModeMap.value[documentId.value] ?? false,
  set: (val) => (documentModeMap.value[documentId.value] = val),
});
//
// const currentDocPermission = await getDocPermissionsByUserId(getUserId() || '', documentId.value);
// // const isReadOnly = ref(currentDocPermission.permissionType === 'READ')
//
// const docPermission = documentStore.fetchDocPermissions(getUserId() || '', documentId.value)
const isSharedPage = computed(() => route.path.includes('/shared/'))

// 权限检查函数
const checkDocPermission = async (docId: string) => {
  if (isSharedPage.value) {
    try {
      const permission = await documentStore.fetchDocPermissions(
          docId,
          getUserId() || ''
      );

      documentModeMap.value[docId] = permission.permissionType === 'READ';

      const editor = editorRef.value?.useEditor();
      if (editor) {
        editor.setEditable(!documentModeMap.value[docId]);
        showBubbleAI.value = !documentModeMap.value[docId];
      }
    } catch (error) {
      console.error('权限获取失败:', error);
      ElMessage.error('获取文档权限失败');
    }
  } else {
    documentModeMap.value[docId] = false;
  }
};

onMounted(() => checkDocPermission(documentId.value));
watch(documentId, (newId) => {checkDocPermission(newId)})

// 切换模式
const toggleEditorMode = () => {
  // 如果是共享页面且只有READ权限，不允许切换模式
  if (isSharedPage.value && isReadOnly.value) {
    ElMessage.warning('您只有查看权限，无法编辑此文档');
    return;
  }

  isReadOnly.value = !isReadOnly.value
  
  // 获取编辑器实例
  const editor = editorRef.value;
  if (editor && editor.useEditor) {
    const tiptapEditor = editor.useEditor();
    if (tiptapEditor) {
      // 设置编辑器为只读模式
      tiptapEditor.setEditable(!isReadOnly.value);
      
      // 如果是只读模式，隐藏AI按钮
      if (isReadOnly.value) {
        showBubbleAI.value = false;
      }
    }
  }
  
  // 显示模式切换提示
  ElMessage.success(isReadOnly.value ? '已进入阅读模式' : '已进入编辑模式');
}

// const { currentDocument } = storeToRefs(documentStore)
// TODO: 只写前端获取不到currentDocument, 用true代替
const currentDocument = ref(true);

//版本表单
const versionFormRef = ref<FormInstance>()

// 版本管理相关状态
const showCreateVersionDialog = ref(false);
const showVersionHistory = ref(false);
const showVersionCompare = ref(false);
const saving = ref(false);
const hasUnsavedChanges = ref(false);
const lastSaveTime = ref<Date | null>(null);
const creatingVersion = ref(false);
const documentVersions = ref<any[]>([]);

// 版本表单
const versionForm = ref({
  versionName: "",
  description: "",
});

const versionRules = {
  versionName: [
    { required: true, message: "请输入版本名称", trigger: "blur" },
    {
      min: 1,
      max: 100,
      message: "版本名称长度为 1-100 个字符",
      trigger: "blur",
    },
  ],
};

watch(
  () => route.params.documentId,
  async (newId) => {
    if (!newId) return;

    try {
      isLoading.value = true;
      // 1. 调用API获取文档内容
      const res = await getDocumentDetail(newId as string, getUserId() || "");
      currentContent.value = res.content;

      // 2. 更新编辑器内容
      if (editorRef.value?.setContent) {
        editorRef.value.setContent(res.content);
      }
    } catch (error) {
      ElMessage.error("文档加载失败");
    } finally {
      isLoading.value = false;
    }
  },
  { immediate: true }
);
const userId = getUserId()
documentStore.fetchDocument(documentId.value,userId || "")

// 页面初始化
/* onMounted(async () => {
  // 加载文档数据
  if (documentId.value) {
    try {
      await documentStore.loadDocument(documentId.value)
    } catch (error) {
      console.error('加载文档失败:', error)
      ElMessage.error('加载文档失败')
    }
  }
}) */


// 修改保存逻辑
// const handleSave = async () => {
//   try {
//     await updateDocument(route.params.documentId as string, {
//       content: editorRef.value?.getContent() || '',
//       lastEditorId: getUserId()?.toString() || ''
//     })
//     ElMessage.success('保存成功')
//   } catch (error) {
//     ElMessage.error('保存失败')
//   }
// }

// 在setup()中添加
const handleEditorSave = async () => {
  if (isSaving.value) {
    return false;
  }
  isSaving.value = true;

  try {
    if (!documentId.value) {
      ElMessage.warning("文档ID不存在");
      console.log(documentId.value);
      return false; // 返回false表示保存失败
    }
    console.log("文档ID：",documentId.value);

    const res = await updateDocument({
      id: Number(documentId.value),
      content: editorRef.value?.getHTML() || "",
      lastEditorId: getUserId()?.toString() || "",
    });

    ElMessage.success("保存成功");
    return true; // 返回true表示保存成功
  } catch (error) {
    console.error("保存失败:", error);
    ElMessage.error("保存失败");
    return false;
  }
};

// UmoEditor 配置
const options = reactive({
  onSave: handleEditorSave, // 关键：注册保存回调
  editable: !isReadOnly.value, // 根据只读状态设置编辑器是否可编辑
  extensions: [
  UmoCollaboration.configure({
      enabled: true,
      documentName:  'collaboration',
      websocketUrl:  'ws://localhost:1234',
      user: {
        name: '用户-' + Math.random().toString(36).substring(2, 8),
        color: '#' + Math.floor(Math.random() * 16777215).toString(16),
      },
      autoSaveInterval: 10000, // 每30秒自动保存一次
      onSave: handleEditorSave, // 传递保存回调
    }),
    CommentHighlight,
  ],
});


const editorRef = ref();
const tiptapEditor = ref();
const summary = ref("");
const summaryVisible = ref(false);
const showCommentSidebar = ref(false);
const showCommentList = ref(false);
const loading = ref(false);
const selectedCommentText = ref("");
const commentsList = ref([]);
const summaryHtml = computed(() => marked.parse(summary.value || ""));
const currentDocumentId = ref(5);

const commentIcon =
  '<svg t="1750927619196" class="icon" viewBox="0 0 1035 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6036" width="200" height="200"><path d="M905.898667 44.032 129.365333 44.032c-71.338667 0-129.365333 58.026667-129.365333 129.365333l0 518.144c0 71.338667 58.026667 129.365333 129.365333 129.365333l253.952 0 134.144 163.84 133.802667-163.84 254.293333 0c71.338667 0 129.365333-58.026667 129.365333-129.365333L1034.922667 173.397333C1035.264 102.058667 977.237333 44.032 905.898667 44.032L905.898667 44.032 905.898667 44.032zM236.885333 498.005333c-34.474667 0-62.464-27.989333-62.464-62.464 0-34.474667 27.989333-62.464 62.464-62.464 34.474667 0 62.464 27.989333 62.464 62.464C299.349333 470.016 271.36 498.005333 236.885333 498.005333L236.885333 498.005333 236.885333 498.005333zM518.144 498.005333c-34.474667 0-62.464-27.989333-62.464-62.464 0-34.474667 27.989333-62.464 62.464-62.464 34.474667 0 62.464 27.989333 62.464 62.464C580.608 470.016 552.618667 498.005333 518.144 498.005333L518.144 498.005333zM799.402667 498.005333c-34.474667 0-62.464-27.989333-62.464-62.464 0-34.474667 27.989333-62.464 62.464-62.464 34.474667 0 62.464 27.989333 62.464 62.464C861.866667 470.016 833.877333 498.005333 799.402667 498.005333L799.402667 498.005333zM799.402667 498.005333" fill="#272636" p-id="6037"></path></svg>';

const listIcon = '<svg t="1751356244666" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5048" width="200" height="200"><path d="M903.872912 0H120.127088A120.127088 120.127088 0 0 0 0 120.127088v783.745824a120.127088 120.127088 0 0 0 120.127088 120.127088h783.745824a120.127088 120.127088 0 0 0 120.127088-120.127088V120.127088A120.127088 120.127088 0 0 0 903.872912 0zM198.126273 822.953971a61.731976 61.731976 0 1 1 61.731975-61.731975 61.731976 61.731976 0 0 1-61.731975 61.731975z m0-250.264765a61.731976 61.731976 0 1 1 61.731975-61.731976 61.731976 61.731976 0 0 1-61.731975 62.566192z m0-250.264766a61.731976 61.731976 0 1 1 61.731975-60.063544 61.731976 61.731976 0 0 1-61.731975 61.731976z m654.025254 467.578004H365.386558a35.454175 35.454175 0 1 1 0-70.491242h486.764969a35.454175 35.454175 0 1 1 0 70.491242z m0-250.264766H365.386558a35.454175 35.454175 0 0 1 0-70.491242h486.764969a35.454175 35.454175 0 1 1 0 70.491242z m0-250.264766H365.386558a35.454175 35.454175 0 1 1 0-70.491242h486.764969a35.454175 35.454175 0 1 1 0 70.491242z" fill="#5E5C5C" p-id="5049"></path></svg>'
let dragOffset = { x: 0, y: 0 };
let dragging = false;

function hasTextSelection() {
  const sel = window.getSelection();
  if (!sel) return false;
  
  const selectedText = sel.toString().trim();
  if (selectedText.length > 0) return true;
  
  // 检查是否有范围选择（即使没有文本内容）
  if (sel.rangeCount > 0) {
    const range = sel.getRangeAt(0);
    if (!range.collapsed) return true;
  }
  
  return false;
}

// 监听 bubble menu 的出现与位置和 selection 变化
onMounted(() => {
  const observer = new MutationObserver(() => {
    updateBubbleAIButton();
  });
  observer.observe(document.body, { childList: true, subtree: true });
  window.addEventListener("scroll", updateBubbleAIButton, true);
  window.addEventListener("resize", updateBubbleAIButton);
  document.addEventListener("selectionchange", updateBubbleAIButton);
  
  // 添加键盘事件监听器，特别处理Ctrl+A全选
  document.addEventListener("keydown", handleKeyDown);
});

// 组件卸载时清理事件监听器
onUnmounted(() => {
  window.removeEventListener("scroll", updateBubbleAIButton, true);
  window.removeEventListener("resize", updateBubbleAIButton);
  document.removeEventListener("selectionchange", updateBubbleAIButton);
  document.removeEventListener("keydown", handleKeyDown);
});

// 处理键盘事件
function handleKeyDown(e: KeyboardEvent) {
  // 检测Ctrl+A (Windows) 或 Cmd+A (Mac)
  if ((e.ctrlKey || e.metaKey) && e.key === 'a') {
    // 延迟执行，确保选择操作完成后再更新UI
    setTimeout(() => {
      updateBubbleAIButton();
    }, 10);
  }
}

function startDrag(e: MouseEvent) {
  dragging = true;
  dragOffset.x = e.clientX - aiResultPosition.x;
  dragOffset.y = e.clientY - aiResultPosition.y;
  document.addEventListener("mousemove", onDrag);
  document.addEventListener("mouseup", stopDrag);
}
function onDrag(e: MouseEvent) {
  if (!dragging) return;
  aiResultPosition.x = e.clientX - dragOffset.x;
  aiResultPosition.y = e.clientY - dragOffset.y;
}
function stopDrag() {
  dragging = false;
  document.removeEventListener("mousemove", onDrag);
  document.removeEventListener("mouseup", stopDrag);
}

const commentListRef = ref<InstanceType<typeof CommentList> | null>(null)
const refreshComments = async () => {
try {
  if (commentListRef.value) {
    await commentListRef.value.fetchComments()
    console.log('评论刷新成功')
  }
} catch (error) {
  console.error('刷新评论失败:', error)
}
}
  
function comment_created(){
  showCommentList.value = true
  // const editor = editorRef.value;
  // tiptapEditor.value = editorRef.value.useEditor();
  // // 取消文本高亮
  // if (editor && editor.getSelectionText) {
  //   tiptapEditor.value.chain().focus().toggleHighlight().run();
  // }
  // editor.setCommentHighlight({
  //   commentId: 'comment-123', // 你的批注ID
  // });
  refreshComments()
}

function handleAddComment (){
    // 在只读模式下不允许添加评论
    if (isReadOnly.value) {
        ElMessage.warning('阅读模式下不能添加评论');
        return;
    }
    
    console.log('按钮被点击') 
    const editor = editorRef.value;
    tiptapEditor.value = editorRef.value.useEditor();
    let selectedText = '';
    if (editor && editor.getSelectionText) {
        selectedText = editor.getSelectionText();
    } else {
        selectedText = window.getSelection()?.toString() || '';
    }
    if (!selectedText) {
        alert('请先选中需要评论的内容');
        return;
    }
    selectedCommentText.value = selectedText;
    showCommentSidebar.value = true;
    
    // 设置选中文本为高亮
    if (editor && editor.getSelectionText) {
      tiptapEditor.value.chain().focus().setHighlight({ color: '#ffff8a' }).run();
    }
    //添加评论按钮 
    
    console.log('准备评论内容:', selectedText);
}

// const fetchAllComments = async (docId: String) => {
//   try {
//     isLoading.value = true
//     const response = await getCommentListAPI(docId)
//     console.log('response:',response)
//     CommentList.value = response.comment_list
//     console.log('commentlist:',response.comment_list)
//   } catch (err) {
//     err.value = err instanceof Error ? err.message : '获取评论时出错'
//     console.error('获取评论失败:', err)
//   } finally {
//     isLoading.value = false
//   }
// }
async function handleSummary() {
  const editor = editorRef.value;
  let selectedText = "";
  if (editor && editor.getSelectionText) {
    selectedText = editor.getSelectionText();
  } else {
    selectedText = window.getSelection()?.toString() || "";
  }
  if (!selectedText) {
    alert("请先选中需要生成摘要的内容");
    return;
  }
  loading.value = true;
  summaryVisible.value = true;
  summary.value = "正在生成摘要...";
  try {
    const res = await fetch(
      "https://one-api-other.nowcoder.com/v1/chat/completions",
      {
        method: "POST",
        headers: {
          Authorization: "sk-iLG1IoQfktTmn1Wm723e91DbF54b4d61970eBa26654eD184",
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        body: JSON.stringify({
          model: "gpt-4o-mini",
          messages: [
            {
              role: "system",
              content:
                "你是一个文档agent,根据文档内容生成智能摘要，摘要字数在100字左右",
            },
            { role: "user", content: selectedText },
          ],
          temperature: 0.7,
        }),
      }
    );
    const data = await res.json();
    summary.value = data.choices?.[0]?.message?.content?.trim() || "生成失败";
  } catch (e) {
    summary.value = "很抱歉，当前系统繁忙，请稍后再试。";
  }
  loading.value = false;
}

// AI功能悬浮框相关
const aiMenuVisible = ref(false);
const aiMenuPosition = reactive({ x: 0, y: 0 });
const aiResultPosition = reactive({ x: 0, y: 0 });
const aiPrompt = ref("");
const aiResultVisible = ref(false);
const aiResult = ref("");
const aiResultHtml = computed(() => marked.parse(aiResult.value || ""));
let lastSelection = "";
let lastRange: Range | null = null; // 新增
const lastAIType = ref("prompt");

// 右键弹出AI功能悬浮框
function handleEditorContextMenu(e: MouseEvent) {
  // 在只读模式下不允许右键菜单
  if (isReadOnly.value) {
    e.preventDefault();
    ElMessage.warning('阅读模式下不能使用右键菜单');
    return;
  }
  
  let selectedText = "";
  const editor = editorRef.value;
  if (editor && editor.getSelectionText) {
    selectedText = editor.getSelectionText();
  } else {
    selectedText = window.getSelection()?.toString() || "";
  }
  if (!selectedText) return;
  lastSelection = selectedText;

  // 保存当前 range
  const sel = window.getSelection();
  lastRange = sel && sel.rangeCount > 0 ? sel.getRangeAt(0).cloneRange() : null;

  aiMenuVisible.value = true;
  aiMenuPosition.x = e.clientX;
  aiMenuPosition.y = e.clientY;
  aiPrompt.value = "";
}

// 处理AI功能
async function handleAIFeature(
  type: "summary" | "continue" | "prompt" | "polish"
) {
  aiMenuVisible.value = false;
  aiResult.value = "AI生成中...";
  aiResultVisible.value = true;
  lastAIType.value = type;
  aiResultPosition.x = aiMenuPosition.x;
  aiResultPosition.y = aiMenuPosition.y;
  let prompt = "";
  if (type === "summary") {
    prompt =
      aiPrompt.value || "请对以下内容生成100字左右摘要：" + lastSelection;
  } else if (type === "continue") {
    prompt = aiPrompt.value || "请根据以下内容续写一段：" + lastSelection;
  } else if (type === "polish") {
    prompt = aiPrompt.value || "请对以下内容进行润色返回润色后结果：" + lastSelection;
  } else if (type === "prompt") {
    prompt = aiPrompt.value + ":" + lastSelection;
  }
  try {
    const res = await fetch(
      "https://one-api-other.nowcoder.com/v1/chat/completions",
      {
        method: "POST",
        headers: {
          Authorization: "sk-iLG1IoQfktTmn1Wm723e91DbF54b4d61970eBa26654eD184",
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        body: JSON.stringify({
          model: "gpt-4o-mini",
          messages: [
            {
              role: "system",
              content: "你是一个文档AI助手，按用户需求处理文本。",
            },
            { role: "user", content: prompt },
          ],
          temperature: 0.7,
        }),
      }
    );
    const data = await res.json();
    aiResult.value = data.choices?.[0]?.message?.content?.trim() || "生成失败";
  } catch (e) {
    aiResult.value = "AI生成失败，请重试";
  }
}
// 插入AI生成内容到编辑器
function insertAIResult() {
  const editor = editorRef.value;
  if (aiResult.value && aiResult.value.startsWith("AI生成中...")) {
    return;
  }
  if (editor && editor.state && editor.commands) {
    const { from, to } = editor.state.selection || {};
    if (lastAIType.value === "summary") {
      editor.commands.insertContentAt(from, aiResult.value);
    } else {
      editor.commands.insertContentAt(to, aiResult.value);
    }
  } else if (lastRange) {
    // 恢复原来的 range
    const sel = window.getSelection();
    sel?.removeAllRanges();
    sel?.addRange(lastRange);
    const range = sel.getRangeAt(0);
    const node = document.createTextNode(aiResult.value);
    if (lastAIType.value === "summary") {
      range.insertNode(node);
    } else {
      range.collapse(false);
      range.insertNode(node);
    }
  }
  aiResultVisible.value = false;
}

// 悬浮AI按钮相关逻辑
const showBubbleAI = ref(false);
const bubbleMenuPos = reactive({ x: 0, y: 0 });
// 监听AI bubble menu 的出现与位置
function updateBubbleAIButton() {
  // 在只读模式下不显示AI按钮
  if (isReadOnly.value) {
    showBubbleAI.value = false;
    return;
  }
  
  // 只在有选中文字时显示
  if (hasTextSelection()) {
    const sel = window.getSelection();
    if (!sel || sel.rangeCount === 0) {
      showBubbleAI.value = false;
      return;
    }
    const range = sel.getRangeAt(0);
    const rect = range.getBoundingClientRect();
    
    // 检查是否是全选（rect可能为空或很小）
    if (rect.width === 0 || rect.height === 0) {
      // 全选时，将按钮放在编辑器中心位置
      const editorElement = document.querySelector('.editor-container');
      if (editorElement) {
        const editorRect = editorElement.getBoundingClientRect();
        bubbleMenuPos.x = editorRect.left + editorRect.width / 2 + window.scrollX;
        bubbleMenuPos.y = editorRect.top + 20 + window.scrollY;
      } else {
        // 备用位置
        bubbleMenuPos.x = window.innerWidth / 2 + window.scrollX;
        bubbleMenuPos.y = 100 + window.scrollY;
      }
    } else {
      // 正常选择，按钮出现在选区右侧
      const btnWidth = 40;
      bubbleMenuPos.x = rect.right + btnWidth + 10 + window.scrollX;
      bubbleMenuPos.y = rect.top - 8 + window.scrollY;
    }
    
    showBubbleAI.value = true;
  } else {
    showBubbleAI.value = false;
  }
}


// 点击AI按钮弹出AI功能
function showAIMenuFromBubble() {
  let selectedText = "";
  const editor = editorRef.value;
  if (editor && editor.getSelectionText) {
    selectedText = editor.getSelectionText();
  } else {
    selectedText = window.getSelection()?.toString() || "";
  }
  lastSelection = selectedText;

  // 保存当前 range
  const sel = window.getSelection();
  lastRange = sel && sel.rangeCount > 0 ? sel.getRangeAt(0).cloneRange() : null;

  showBubbleAI.value = false;
  aiMenuVisible.value = true;
  aiMenuPosition.x = bubbleMenuPos.x + 48;
  aiMenuPosition.y = bubbleMenuPos.y;
  aiPrompt.value = "";
}


  // 创建版本处理
const handleCreateVersionClick = async () => {
  try {
    await versionFormRef.value?.validate()
    
    creatingVersion.value = true
    
    await documentStore.createNewDocumentVersion(documentId.value, versionForm.value, userId || "")
    
    ElMessage.success('版本创建成功')
    showCreateVersionDialog.value = false
    resetVersionForm()
    
  } catch (error) {
    console.error('创建版本失败:', error)
    if (error instanceof Error) {
      ElMessage.error('创建版本失败: ' + error.message)
    } else {
      ElMessage.error('创建版本失败，请重试')
    }
  } finally {
    creatingVersion.value = false
  }
}

// 重置版本表单
const resetVersionForm = () => {
  versionFormRef.value?.resetFields()
  versionForm.value = {
    versionName: '',
    description: ''
  }
}

// 版本历史处理
const handleVersionRestored = async () => {
  // 版本恢复后重新加载文档内容
  try {
    await documentStore.fetchDocument(documentId.value, userId || "")
    ElMessage.success('文档已恢复')
    showVersionHistory.value = false
    
    // 立即刷新页面
    window.location.reload()
    
  } catch (error) {
    console.error('重新加载文档失败:', error)
    ElMessage.error('重新加载文档失败')
  }
}

// 加载文档版本列表
const loadDocumentVersions = async () => {
  if (!documentId.value) return
  
  try {
    documentVersions.value = await getDocumentVersions(documentId.value)
  } catch (error) {
    console.error('加载版本列表失败:', error)
    ElMessage.error('加载版本列表失败')
  }
}

// 监听版本对比对话框显示状态
watch(showVersionCompare, (visible: boolean) => {
  if (visible) {
    loadDocumentVersions()
  }
})

// 返回上一页
const goBack = () => {
  router.back()
}
</script>

<style scoped>
.editor-container {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  position: relative;
  display: flex;
  flex-direction: column;
}

.editor-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 24px;
  border-bottom: 1px solid #e4e7ed;
  background: #fff;
  z-index: 100;
  flex-shrink: 0;

  .toolbar-left {
    display: flex;
    align-items: center;
    gap: 16px;

    .document-title {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }

    .document-status {
      font-size: 12px;
    }

    .last-save-time {
      font-size: 12px;
      color: #909399;
    }
  }

  .toolbar-right {
    display: flex;
    align-items: center;
    gap: 8px;

    .version-info {
      font-size: 12px;
      color: #909399;
      padding: 4px 8px;
      background: #f5f7fa;
      border-radius: 4px;
      margin-left: 8px;
    }
  }
}

.toolbar {
  position: absolute;
  top: 300px;
  left: 100px;
  z-index: 10;
  background: #a0c5fa;
}
.toolbar button {
  background: #1677ff;
  color: #fff;
  border: none;
  padding: 8px 20px;
  border-radius: 4px;
  font-weight: bold;
  cursor: pointer;
  transition: background 0.2s;
}
.summary-sidebar {
  position: fixed;
  top: 250px;
  right: 0;
  width: 320px;
  height: 40vh;
  background: #fafbfc;
  border-left: 1px solid #eee;
  padding: 16px 16px 0 16px;
  z-index: 9999;
  box-shadow: -2px 0 8px #eee;
  border-radius: 8px 0 0 8px;
  display: flex;
  flex-direction: column;
}
.summary-content {
  flex: 1 1 0;
  overflow-y: auto;
  white-space: pre-wrap;
  margin-bottom: 16px;
}
.close-btn {
  width: 56px;
  min-width: 40px;
  padding: 6px 0;
  font-size: 15px;
  font-weight: 500;
  background: #fff;
  color: #ff4d4f;
  border: 1.5px solid #ff4d4f;
  border-radius: 6px;
  cursor: pointer;
  margin: 0;
  transition: background 0.2s, color 0.2s;
  display: inline-block;
  text-align: center;
}
.close-btn:hover {
  background: #ff4d4f;
  color: #fff;
}

.ai-menu-popup {
  position: fixed;
  z-index: 99999;
  background: #fff;
  border: 1px solid #eee;
  box-shadow: 0 2px 8px #ccc;
  padding: 16px 16px 12px 16px;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  min-width: 260px;
  max-width: 320px;
}
.ai-prompt-input {
  width: 100%;
  box-sizing: border-box;
  padding: 6px 10px;
  border: 1px solid #d0d0d0;
  border-radius: 6px;
  font-size: 15px;
  outline: none;
  margin-bottom: 2px;
}
.ai-menu-popup .ai-btn {
  width: 100%;
  background: #fff;
  color: #1677ff;
  border: 1.5px solid #1677ff;
  border-radius: 6px;
  padding: 10px 0;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  margin-bottom: 2px;
  transition: background 0.2s, color 0.2s;
}
.ai-menu-popup .ai-btn:hover {
  background: #1677ff;
  color: #fff;
}
.ai-menu-popup .close-btn {
  width: 100%;
  background: #fff;
  color: #ff4d4f;
  border: 1.5px solid #ff4d4f;
  border-radius: 6px;
  padding: 10px 0;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  margin-top: 4px;
  transition: background 0.2s, color 0.2s;
}
.ai-menu-popup .close-btn:hover {
  background: #ff4d4f;
  color: #fff;
}
.ai-result-modal {
  max-width: 360px;
  min-width: 260px;
  z-index: 100000;
  background: #fff;
  border: 1px solid #eee;
  box-shadow: 0 2px 8px #ccc;
  padding: 24px;
  border-radius: 8px;
  /* 新增：最大高度和滚动 */
  max-height: 60vh;
  overflow: auto;
}

.ai-result-content {
  /* 新增：内容区最大高度和滚动 */
  max-height: 40vh;
  overflow-y: auto;
  white-space: pre-wrap;
  word-break: break-all;
}

.ai-result-modal-header {
  cursor: move;
  font-weight: bold;
  padding: 6px 0 10px 0;
  user-select: none;
}

.bubble-ai-btn-absolute {
  position: fixed;
  z-index: 99999;
  background: #fff;
  border: 1px solid #1677ff;
  color: #1677ff;
  border-radius: 6px;
  padding: 4px 10px;
  margin: 0 4px;
  cursor: pointer;
  font-weight: 500;
  display: flex;
  align-items: center;
  transition: background 0.2s, color 0.2s;
}
.bubble-ai-btn-absolute:hover {
  background: #1677ff;
  color: #fff;
}

.comment {
  background-color: red;
  cursor: pointer;
}

/* 只读模式样式 */
.editor-container.readonly {
  opacity: 0.9;
}

.editor-container.readonly .editor-toolbar {
  background-color: #f5f5f5;
}

.editor-container.readonly .umo-editor {
  background-color: #fafafa;
  border: 1px solid #e0e0e0;
  cursor: default;
}

.editor-container.readonly .umo-editor * {
  user-select: text;
  -webkit-user-select: text;
  -moz-user-select: text;
  -ms-user-select: text;
}
</style>
